package com.zdp.degisn.pipe_filter.utils;

import com.zdp.degisn.pipe_filter.FilterPipe;
import com.zdp.degisn.pipe_filter.filter.Filter;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.ServiceLoader;

/**
 * @author zhengdp
 * @Description spi加载类
 * @Date 2022/8/28 18:15
 * @Created by zhengdp
 */
public class FilterPipeUtils {

    private static FilterPipe instance;

    private FilterPipeUtils(){
    }

    // 双重检测锁
    public static FilterPipe instance(){
        if(Objects.isNull(instance)){
            synchronized (FilterPipeUtils.class){
                if(Objects.isNull(instance)){
                    instance = buildInstance();
                }
            }
        }
        return instance;
    }

    private static FilterPipe buildInstance(){
        List<Filter> filters = new ArrayList<>();
        ServiceLoader<Filter> load = ServiceLoader.load(Filter.class);
        for(Filter filter : load){
            filters.add(filter);
        }
        // 根据Order进行排序
        filters.sort((o1,o2)->o2.getOrder() - o1.getOrder());
        instance = new FilterPipe();
        filters.forEach(instance::addFirst);
        return instance;
    }


}
